import React, { Component } from 'react'
import PropTypes from 'prop-types';
import { connect } from 'react-redux'
import {
  List,
  Badge
} from 'antd-mobile'

import './message.scss'

const ListItem = List.Item
const Brief = ListItem.Brief

// 获取与每个对话者的最后消息、统计未读数量
function getLastMessage(chatMsgs, userId) {
  // 所有对应的最后消息的对象
  const lastMsgsObj = {}

  chatMsgs.forEach((msg) => {
    // 每个消息添加未读数量
    msg.unreadCount = !msg.read && msg.to === userId ? 1 : 0
    
    // 获取改聊天id对应的当前已存在最后消息对象里的数据
    const chatId = msg.chat_id
    const currentLastMsg = lastMsgsObj[chatId]
    if (!currentLastMsg) { 
      // 不存在当前的最后消息，把当前循环的消息赋给最后消息
      lastMsgsObj[chatId] = msg
    } else{
      // 已经存在，对比两个消息的时间决定谁是最后消息
      const newCurrentLastMsg = currentLastMsg.create_time > msg.create_time ? currentLastMsg : msg
      // 累加未读消息数量
      newCurrentLastMsg.unreadCount = currentLastMsg.unreadCount + msg.unreadCount
      lastMsgsObj[chatId] = newCurrentLastMsg
    }
  })

  // 获取所有最后消息的数组，然后按时间降序排序
  const lastMessages = Object.values(lastMsgsObj)
  lastMessages.sort((msg1, msg2) => msg2.create_time - msg1.create_time )

  return lastMessages
}


export class Message extends Component {
  static propTypes = {
    user: PropTypes.object.isRequired,
    chat: PropTypes.object.isRequired
  }
  render() {
    const { user, getMessageList_ } = this.props
    const {users, chatMsgs} = this.props.chat
    // 获取每组对话最后消息
    const lastMessages =  getLastMessage(chatMsgs, user._id)
    return (
      <div id="message-page" >
        <List>
          {
            lastMessages.map( (msg) => {
              // 获取改聊天的对话者id
              const targetId = msg.from === user._id ? msg.to : msg.from
              if (!users[targetId]) {
                // 进入该判断说明列表里还没有该消息用户的信息，该用户为刚注册给当前客户端发消息
                getMessageList_()
              }
              // 获取对话者名字和头像
              const targetName = users[targetId].username
              const targetHeader = users[targetId].header
              const targetHeaderImg = require(`../../assets/images/${targetHeader}.png`)
              return (
                <ListItem
                  key={msg._id}
                  extra={<Badge text={msg.unreadCount} overflowCount={99} />}
                  arrow="horizontal"
                  thumb={ <img src={targetHeaderImg} className="header-img" alt=""/> }
                  multipleLine
                  onClick={() => {this.props.history.push(`/chat/${targetId}`)}}
                >
                  {targetName} 
                  <Brief>{msg.content}</Brief>
                </ListItem>
              )
            })
          }
        </List>
      </div>
    )
  }
}

export default connect(
  state => ({ user: state.user, chat: state.chat }),
  {}
)(Message)